package conn

import (
	"chatting/model"
	"fmt"
	"github.com/gogf/gf/v2/net/gtcp"
	"log"
)

type Server struct {
	*gtcp.Server
	OnlineUsers map[string]*gtcp.Conn
}

//NewServer 新建一个服务端，心跳统一规定是客户端ping服务端
func NewServer() *Server {
	s := new(Server)
	s.OnlineUsers = make(map[string]*gtcp.Conn, 0)
	return s
}

func (server *Server) Run(addr string) {
	s := gtcp.NewServer(addr, func(conn *gtcp.Conn) {
		defer func() {
			conn.Close()
			for k, v := range server.OnlineUsers {
				if v == conn {
					delete(server.OnlineUsers, k)
					fmt.Println("删除链接", k)
				}
			}
		}()
		for {
			pkg, err := conn.RecvPkg()
			if err != nil {
				fmt.Println(err)
				break
			}
			msg := model.UnPackageToMessage(pkg)
			//fmt.Println("是什么类型的捏", msg.Typeis())
			switch msg.Typeis() {
			case model.Register:
				server.RegisterHandle(conn, msg.(*model.RegisterMessage))
			case model.Login:
				server.LoginHandle(conn, msg.(*model.LoginMessage))
			case model.Chat:
				server.ChatHandle(conn, msg.(*model.ChatMessage))
			case model.Ping:
				server.PingHandle(conn)
			}
		}
	})
	server.Server = s
	log.Println("server Run AT " + addr)
	s.Run()
}
